//
//  WBAuthViewController.swift
//  Weibo
//
//  Created by kobe on 2016/12/24.
//  Copyright © 2016年 kobe. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBAuthViewController: UIViewController {
    
    fileprivate lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        view.backgroundColor = UIColor.white
        
        //取消webview滚动
        webView.scrollView.isScrollEnabled = false
        
        webView.delegate = self
        
        //设置导航栏
        title = "登录新浪微博"
        //导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
        
        guard let url = URL(string:urlStr) else {
            return
        }
    
        let request = URLRequest(url: url)
        
        webView.loadRequest(request)
        
        
    }
    
    @objc fileprivate func autoFill() {
        //准备js
        let js = "document.getElementById('userId').value = '407279751@qq.com';" + "document.getElementById('passwd').value = 'liwei18571369958';"
        
//        webview执行js
        webView.stringByEvaluatingJavaScript(from: js)
    }
    
    func close() {

        SVProgressHUD.dismiss()

        dismiss(animated: true, completion: nil)
    }


}

extension WBAuthViewController:UIWebViewDelegate {
    
    /// webview 将要加载请求
    ///
    /// - parameter webView:        webview
    /// - parameter request:        要加载的请求
    /// - parameter navigationType: 导航类型
    ///
    /// - returns: 是否加载request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if request.url?.absoluteString.hasPrefix(WBRedirectURI) == false {
            
            return true
        }
        
//        print("加载请求--\(request.url?.absoluteString)")
//        print("加载请求--\(request.url?.query)")
        
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            close()
            return false
        }
        
        //从query字符串中取出授权码
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        let vc = WBBaseViewController()
        vc.userLogin = true
//        UIApplication.shared.delegate?.window
        
        print("获取授权码 \(code)")
        
        // 使用授权码来获取 token
        WBNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            
            if !isSuccess {
                SVProgressHUD .showInfo(withStatus: "网络请求失败")
            } else {
                //跳转界面,通知 发送登录成功消息
                NotificationCenter.default.post(name: Notification.Name(rawValue:WBUserLoginSuccessNotification), object: nil)
                
                //关闭窗口
                self.close()
                
                
            }
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD .show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD .dismiss()
    }
}


